<template>
    <el-drawer v-model="docDrawer" :modal="modal" :direction="direction" :size="getSize" :showClose="showClose"
        :before-close="handleClose" :modal-class="getModalClass" :class="getCustomClass">
        <template #header>
            <div class="drawer-title">{{ $t('message.text.folderSetting') }}</div>
            <svg class="drawer-close" v-if="!showClose" @click="handleClose">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </template>
        <div class="doc-set-body">
            <div class="nav-list">
                <el-scrollbar>
                    <div v-for="(item, index) in navList" :key="index" class="nav-item"
                        :class="[item.value == navActive.value && 'nav-active']" @click="changeNav(item)">
                        <svg class="nav-icon">
                            <use v-bind:xlink:href="`#${item.value != navActive.value ? item.icon : item.iconActive}`"></use>
                        </svg>
                        {{ $t(item.label) }}
                    </div>
                </el-scrollbar>
            </div>
            <div class="nav-body" v-loading="bodyLoading">
                <div class="nav-title">{{ $t(navActive.label) }}</div>
                <div class="nav-content">
                    <el-scrollbar ref="navBodyRef"
                        :max-height="navActive.value == 'knowInfo' ? 'calc(100vh - 130px)' : 'calc(100vh - 190px)'">
                        <div class="base-info" v-show="navActive.value == 'knowInfo'">
                            <div class="set-item">
                                <span class="item-name">{{ $t('message.form.folderName') }}</span>
                            </div>
                            <div class="file-name-input-box marginBot30" :class="[isEdit && 'file-name-edit']">
                                <el-input v-model="editName" :placeholder="$t('message.placeholder.pleaseFolderName')"
                                    ref="inputBox" :readonly="!isEdit" @blur="inputBlur"></el-input>
                                <svg class="edit-icon"
                                    v-if="!isEdit && $permissionRole('document_update', docInfo.dcIdentifying)"
                                    @click="changeEdit">
                                    <use xlink:href="#keowledge-bianji"></use>
                                </svg>
                            </div>
                            <docShare :openShare="docInfo.shareRole" rendeId="dir-qcode-box" initId="dirShareQcode"
                                v-model:docInfo="docInfo" class="doc-share-box"></docShare>
                        </div>
                        <div class="auth-box" v-show="navActive.value == 'auth'">
                            <permissionRole ref="permissionRef" custom-class="sticky-header"
                                :disabled="!$permissionRole('document_auth_settings', docInfo.dcIdentifying)"
                                :infoData="docInfo" :role="persRoleList" :roleType="docInfo.roleType"
                                :roleList="permRoleList"></permissionRole>
                        </div>
                        <div class="message-box" v-show="navActive.value == 'message'">
                            <message-push ref="messagePushRef" @changeMessageStatus="changeMessageStatus"
                                :knowForm="docInfo" :title="$t('message.text.document')"></message-push>
                        </div>
                    </el-scrollbar>
                </div>
                <div class="button-box"
                    v-if="navActive.value != 'knowInfo' && $permissionRole('document_auth_settings', docInfo.dcIdentifying)">
                    <el-button type="primary" @click="submit"
                        :loading="submitLoading">{{ $t('message.buttons.saveSetting') }}</el-button>
                    <el-button @click="handleClose">{{ $t('message.buttons.cancal') }}</el-button>
                </div>
            </div>
        </div>
    </el-drawer>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    nextTick,
    getCurrentInstance,
    computed
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import { useRouter } from "vue-router"
import { getByIdShareInfo, setLibrary, shareSetting } from '@/api/common'
import { enCodeKey } from "@/const/const"
import { encryption, decryption, randomLenNum } from "@/utils/util";
import { getAuthList, getDocAuthId } from '@/api/role'
import docShare from './docShare.vue'
import permissionRole from '@/views/common/permission.vue'
import messagePush from '@/views/common/messagePush.vue'
import { messageSave, messageIsPush } from '@/api/message'
import { $permissionRole } from '@/utils/role'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const router = useRouter();

const emit = defineEmits([""])
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const props = defineProps({
    direction: {
        type: String,
        default: 'rtl'
    },
    remove: Function,
    hasModal: {
        type: Boolean,
        default: true
    },
    modalTrans: {
        type: Boolean,
        default: true
    },
    showClose: {
        type: Boolean,
        default: false
    },
    width: {
        type: [Number, String],
        default: '800px'
    },
    showHeaderBorder: {
        type: Boolean,
        default: true
    },
    docInfo: {
        type: Object,
        default() {
            return {}
        }
    }
})
const navList = ref([
    {
        label: 'message.text.baisSetting',
        value: 'knowInfo',
        icon: 'keowledge-wenkuxinxi',
        iconActive: 'keowledge-a-wenkuxinxi1'
    },
    {
        label: 'message.text.folderAuth',
        value: 'auth',
        icon: 'keowledge-wenkuquanxian',
        iconActive: 'keowledge-a-wenkuquanxian1'
    },
    // {
    //     label:'消息设置',
    //     value:'message',
    //     icon:'keowledge-xiaoximoban',
    //     iconActive:'keowledge-a-xiaoximoban1'
    // },
])
const navActive = ref({
    label: 'message.tooltips.knowInfo',
    value: 'knowInfo',
    icon: '',
    iconActive: ''
})
const isEdit = ref(false)
const editName = ref('')
const inputBox = ref()
const docInfo = ref({
    share: false,
    commentable: false,
    security: false,
    shareTimeType: 'PERPETUAL',
    sharePassword: '',
    showShareLink: '',
    addAuthConfigDto: [],
    readNotify: false,
})
const bodyLoading = ref(false)
const permRoleList = ref([])
const persRoleList = ref([])
const permissionRef = ref()
const getAuthorityFirst = ref(true)
const messagePushRef = ref()
const modal = computed(() => {
    return props.hasModal
})
const getSize = computed(() => {
    return props.width
})
const submitLoading = ref(false)
const getModalClass = computed(() => {
    if (props.modalTrans) {
        return 'modal-trans'
    } else {
        ''
    }
})
const getCustomClass = computed(() => {
    let str = 'custom-docset-drawer'
    if (props.showHeaderBorder) {
        str += ' show-drawer-border'
    }
    return str
})
const docDrawer = ref(false)
const shareFocus = ref(false)
onMounted(() => {
    docInfo.value = Object.assign({}, docInfo.value, props.docInfo, {
        share: false
    })
    editName.value = docInfo.value.name
    init()
})
function init() {
    docDrawer.value = true
    getByIdShareInfo(docInfo.value.id).then(res => {
        if (res.data.code == 0) {
            if (res.data.data.share) {
                docInfo.value.showShareLink = `${location.origin}/#/share/` + res.data.data.shareLink
            }
            docInfo.value = Object.assign({}, docInfo.value, res.data.data)
            if (docInfo.value.sharePassword) {
                let temp = decryption({
                    data: { pass: docInfo.value.sharePassword },
                    key: enCodeKey,
                    param: ["pass"]
                });
                if (!docInfo.value.shareTimeType) docInfo.value.shareTimeType = 'PERPETUAL'
                docInfo.value.sharePassword = temp.pass
                docInfo.value.security = true
            }
        }
    })
}
async function changeNav(item) {
    submitLoading.value = false
    if (navActive.value.value == 'auth') {
        getAuthData()
    }
    navActive.value = item
    if (item.value == 'auth') {
        bodyLoading.value = true
        if (getAuthorityFirst.value) {
            await getAuthority()
        } else {
            permissionRef.value.init()
        }
        await getAuthNameList('document')
    }
    if (item.value == 'message') {
        let userInfoList: any[] = []
        const permissionData = permissionRef.value.getPermissionData()
        permissionData.role.map((item: any, index: number) => {
            userInfoList.push(...item.userInfoList)
        })
        messagePushRef.value.setRoleList(userInfoList)
        messagePushRef.value.init()
    }
}
function getAuthData(isSave = false) {
    const getPermissionData = permissionRef.value?.getPermissionData()
    docInfo.value.addAuthConfigDto = getPermissionData.role.map((item, index) => {
        let obj = {
            idcIdentifying: [],
            userInfoList: []
        }
        item.userInfoList.map((itemP, indexP) => {
            itemP.userId = itemP.id
            itemP.dataAuthType = itemP.type
        })
        obj.userInfoList.push(...item.userInfoList)
        obj.idcIdentifying.push(...item.idcIdentifying)
        return obj
    })
    persRoleList.value = docInfo.value.addAuthConfigDto
    if (isSave) {
        submitLoading.value = true
        saveInfo($t('message.message.savePermissionSuccess'))
    }
}
function getAuthority() {
    getDocAuthId(docInfo.value.id).then(res => {
        if (res.data.code == 0) {
            persRoleList.value = res.data.data
        }
    }).finally(res => {
        bodyLoading.value = false
        getAuthorityFirst.value = false
        permissionRef.value.init()
    })
}
function getAuthNameList(type: any) {
    getAuthList({
        type: type
    }).then(res => {
        if (res.data.code == 0) {
            if (docInfo.value.type != 'directory') {
                permRoleList.value = res.data.data
            } else {
                permRoleList.value = res.data.data.filter(item => item.identifyingKey.indexOf('library_') == -1)
            }
            nextTick(() => {
                permissionRef.value && permissionRef.value.init()
                bodyLoading.value = false
            })
        }
    }).catch(err => {
        bodyLoading.value = false
    })
}
function shareChange(val) {
    let obj = {
        id: docInfo.value.id,
        dcId: docInfo.value.id,
        settingType: '',
        shareLinkOriginal: '',
        sharePassword: '',
        share: val,
        updatePassWord: false,
        shareTimeType: 'PERPETUAL'
    }
    if (val) {
        obj.settingType = 'CREATE_URL'
        obj.shareLinkOriginal = `knId=${docInfo.value.knowledgeId}&type=${docInfo.value.type}&nameSuffix=${docInfo.value.nameSuffix || ''}&docId=${docInfo.value.docId || docInfo.value.id}`
    } else {
        docInfo.value.security = false
        obj.settingType = 'SHARE'
    }
    sendShareSet(obj)
}
function sendShareSet(obj) {
    let temp = encryption({
        data: obj,
        key: enCodeKey,
        param: ["sharePassword"]
    });
    shareSetting(temp).then(res => {
        if (res.data.code == 0) {
            if (obj.share) {
                docInfo.value.showShareLink = `${location.origin}/#/share/` + res.data.data.shareLink
            }
            proxy.$eventBus.$emit("refreshItemStatus", 'valChange', {
                id: docInfo.value.id,
                key: 'share',
                changeVal: obj.share
            })
        }
    })
}
function commentChange(val) {
    sendSetDocInfo({
        ...docInfo.value,
        commentable: val
    }, 'commentable', val)
}
function handleClose() {
    docDrawer.value = false
}
function inputBlur() {
    isEdit.value = false
    if (!editName.value) {
        editName.value = docInfo.value.name
    } else if (editName.value != docInfo.value.name) {
        sendSetDocInfo({
            ...docInfo.value,
            name: editName.value
        }, 'name', editName.value)
    }
}
function sendSetDocInfo(data, key, val) {
    setLibrary(data).then(res => {
        if (res.data.code == 0) {
            docInfo.value[key] = val
            // 修改了值后要同步修改树
            proxy.$eventBus.$emit("refreshItemStatus", 'valChange', {
                id: docInfo.value.id,
                key: key,
                changeVal: val
            })
        }
    })
}
function changeEdit() {
    isEdit.value = true
    inputBox.value.focus()
}
function sharePassFocus() {
    shareFocus.value = true
}
function sharePassBlur() {
    shareFocus.value = false
    passwordChange(true, docInfo.value.sharePassword)
}
function changeMessageStatus(item) {
    docInfo.value.readNotify = item.value
}
function passwordChange(val, pwd) {
    if (pwd) {
        docInfo.value.sharePassword = pwd
    } else {
        if (val) {
            docInfo.value.sharePassword = randomLenNum()
        } else {
            docInfo.value.sharePassword = ''
        }
    }
    let obj = {
        id: docInfo.value.id,
        dcId: docInfo.value.id,
        settingType: 'PWD',
        shareLinkOriginal: `knId=${docInfo.value.knowledgeId}&type=${docInfo.value.type}&nameSuffix=${docInfo.value.nameSuffix || ''}&docId=${docInfo.value.docId || docInfo.value.id}`,
        sharePassword: docInfo.value.sharePassword,
        share: docInfo.value.share,
        updatePassWord: true,
        shareTimeType: 'PERPETUAL'
    }
    sendShareSet(obj)
}
function submit() {
    switch (navActive.value.value) {
        case 'auth':
            getAuthData(true)
            break;
        case 'message':
            submitLoading.value = true
            let messageList = messagePushRef.value.getMessageList()
            messageList.forEach(element => {
                element.facilitator = element.messageType
                element.businessId = docInfo.value.id
            });
            messageSave(messageList, docInfo.value.id).then(res => {
                if (res.data.code == 0) {
                    if (docInfo.value.readNotify) {
                        proxy.$onePrompt.$oneNotify({
                            message: $t('message.message.saveMessageSuccess'),
                            title: $t('message.prompt'),
                            type: "success",
                            position: 'bottom-right'
                        })
                    }
                    submitLoading.value = false
                }
            })
            if (docInfo.value.readNotify != props.docInfo.readNotify) {
                messageIsPush({
                    id: docInfo.value.id,
                    readNotify: docInfo.value.readNotify
                }).then(res => {
                    if (!docInfo.value.readNotify) {
                        proxy.$onePrompt.$oneNotify({
                            message: $t('message.message.closeMessage'),
                            title: $t('message.prompt'),
                            type: "success",
                            position: 'bottom-right'
                        })
                    }
                    proxy.$eventBus.$emit("refreshItemStatus", 'valChange', {
                        id: docInfo.value.id,
                        key: 'readNotify',
                        changeVal: docInfo.value.readNotify
                    })
                    submitLoading.value = false
                })
            }
            break;
        default:
            break;
    }
}
function saveInfo(message: string) {
    setLibrary(docInfo.value).then(res => {
        if (res.data.code == 0) {
            proxy.$onePrompt.$oneNotify({
                message: message,
                title: $t('message.prompt'),
                type: "success",
                position: 'bottom-right'
            })
            submitLoading.value = false
        }
    })
}
</script>
<style lang="scss">
.custom-docset-drawer {
    .el-drawer__header {
        padding: 24px 24px 0px;
        margin-bottom: 16px;

        .drawer-title {
            font-size: 20px;
            color: #363b4c;
            @include SourceHanSansCN-Bold;
        }

        .drawer-close {
            width: 16px;
            height: 16px;
            cursor: pointer;
        }
    }

    .el-drawer__body {
        padding: 0px !important;

        .doc-set-body {
            display: flex;
            height: 100%;
            width: 100%;

            .nav-list {
                width: 168px;
                height: 100%;
                background: #F5F6F7;
                padding: 23px 8px 0px;
                box-sizing: border-box;

                .nav-item {
                    border-radius: 4px;
                    height: 36px;
                    display: flex;
                    align-items: center;
                    font-size: 14px;
                    @include SourceHanSansCN-Regular;
                    color: #363b4c;
                    padding: 0px 16px;
                    box-sizing: border-box;
                    cursor: pointer;

                    .nav-icon {
                        width: 16px;
                        height: 16px;
                        margin-right: 8px;
                    }

                    &:hover {
                        background-color: #eeeff0;
                    }
                }

                .nav-item+.nav-item {
                    margin-top: 14px;
                }

                .nav-active {
                    background: #DDEAFF !important;
                    color: #1E6FFF;
                }
            }

            .nav-body {
                width: calc(100% - 168px);
                height: 100%;

                .nav-title {
                    font-size: 16px;
                    color: #363b4c;
                    @include SourceHanSansCN-Bold;
                    padding: 24px 24px 8px;
                }

                .nav-content {
                    .message-box {
                        padding: 0px 24px 16px;

                        .message-type-box {
                            .message-item {
                                display: flex;
                                align-items: center;
                                font-size: 14px;
                                color: #363b4c;
                                @include SourceHanSansCN-Regular;

                                span {
                                    cursor: pointer;
                                }

                                .radio-icon {
                                    width: 14px;
                                    height: 14px;
                                    margin-right: 12px;
                                }
                            }

                            .message-item+.message-item {
                                margin-top: 8px;
                            }
                        }
                    }

                    .base-info {
                        .set-item {
                            padding: 0px 24px;
                            display: flex;
                            align-items: center;
                            justify-content: space-between;

                            .item-name {
                                color: #363b4c;
                                font-size: 14px;
                                @include SourceHanSansCN-Bold;
                            }

                            .input-box {
                                width: 100%;
                                margin-right: 16px;
                                background: #F5F6F7;
                                border: 1px solid #f5f6f7;
                                border-radius: 6px 6px 6px 6px;
                                padding: 0px 4px;
                                height: 36px;
                                display: flex;
                                align-items: center;

                                .el-input {
                                    .el-input__wrapper {
                                        box-shadow: none !important;
                                        background-color: transparent !important;
                                    }
                                }
                            }

                            .input-box-focus {
                                border-color: #1E6FFF;
                            }
                        }

                        .file-name-input-box {
                            height: 36px;
                            background-color: #f5f6f7;
                            border-radius: 6px;
                            margin: 8px 24px;
                            display: flex;
                            align-items: center;
                            padding: 0px 16px 0px 4px;
                            border: 1px solid #f5f6f7;

                            .edit-icon {
                                width: 16px;
                                height: 16px;
                                min-width: 16px;
                                cursor: pointer;
                            }

                            .el-input {
                                .el-input__wrapper {
                                    box-shadow: none;
                                    background: transparent;
                                }
                            }
                        }

                        .marginBot30 {
                            margin-bottom: 30px;
                        }

                        .file-name-edit {
                            border-color: #1E6FFF;
                        }

                        .set-item-tips {
                            padding: 0px 24px;
                            color: #6F7588;
                            font-size: 12px;
                        }
                    }

                    .auth-box {
                        padding: 0px 24px 16px;

                        .role-box {
                            .role-item {
                                cursor: pointer;
                                display: flex;
                                align-items: center;
                                padding: 8px 0px;

                                .icon {
                                    width: 14px;
                                    height: 14px;
                                    margin-right: 12px;
                                }
                            }
                        }

                        .link-copy-url-box {
                            display: flex;
                            align-items: center;
                            padding-left: 22px;

                            .link-url-box {
                                width: 297px;
                                height: 36px;
                                line-height: 36px;
                                background: #F5F6F7;
                                border-radius: 6px 6px 6px 6px;
                                margin-right: 8px;
                                padding: 0px 12px;
                                overflow: hidden;
                                white-space: nowrap;
                                text-overflow: ellipsis;
                                cursor: pointer;
                            }
                        }
                    }

                    .item-title {
                        color: #363B4C;
                        font-size: 14px;
                        @include SourceHanSansCN-Bold;
                        margin-bottom: 8px;
                        margin-top: 16px;
                        display: flex;
                        align-items: center;
                        justify-content: space-between;

                        .title {
                            color: #363B4C;
                            font-size: 14px;
                            @include SourceHanSansCN-Bold;
                        }

                        .add-auth {
                            color: #1E6FFF;
                            @include SourceHanSansCN-Regular;
                            cursor: pointer;
                            display: flex;
                            align-items: center;
                            user-select: none;
                        }

                    }

                    .title-tips {
                        justify-content: start !important;

                        .tips {
                            color: #6F7588;
                            font-size: 12px;
                        }
                    }

                    .sticky-header {
                        position: sticky;
                        top: 0px;
                        margin: 0px;
                        padding: 16px 0px 8px;
                        background-color: #fff;
                        z-index: 9;
                    }
                }

                .button-box {
                    padding: 14px 24px;
                }
            }
        }
    }
}
</style>